<template>
  <div>
    <BasicModal @register="register" v-bind="$attrs" :helpMessage="'提示1'" @ok="okClick">
      <BasicForm @register="registerForm">
        <template #tenantConfigurationSlot>
          <div class="flex">
            <Select
              v-model:value="tenantConSelect"
              show-search
              :options="selectOption"
              :max-tag-count="3"
              allow_clear
              :filter-option="filterOption"
            ></Select>
          </div>
        </template>
      </BasicForm>
    </BasicModal>
  </div>
</template>

<script setup lang="ts">
  import { Select, SelectProps } from 'ant-design-vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm, FormSchema } from '/@/components/Form';
  import { ref } from 'vue';
  import { modalFormStyleSetting, modalStyleSetting } from '/@/settings/thingsBoardDesign';
  import {
    addTheTenant,
    getTenantProfileInfo,
    getTheTenantById,
    getTenantProfileInfoList,
    getTenantProfile,
  } from '/@/api/thingsborad/tenant/tenant';
  // 组件通信
  const emits = defineEmits(['closeModelFlag']);
  // 租户配置选择
  let tenantConSelect = ref<any>();
  // 租户配置选项数据
  let selectOption = ref<SelectProps['options']>([]);
  // 登录id
  let tenantProfileId = ref<any>();
  //用户数据
  let customerData = ref<any>();
  //打开弹窗的方式
  let isEdit = ref<boolean>(false);
  // 配置文件搜索选项
  const filterOption = (input: string, option: any) => {
    return option.value.toLowerCase().indexOf(input.toLowerCase()) >= 0;
  };
  //表格字段
  const schemas: FormSchema[] = [
    {
      field: 'addCustomerTitle',
      required: true,
      component: 'Input',
      label: '标题',
      componentProps: {
        placeholder: '请输入标题',
      },
    },
    {
      field: 'tenantConfiguration',
      slot: 'tenantConfigurationSlot',
      component: 'Input',
      label: '租户配置',
    },
    {
      field: 'EMail',
      component: 'Input',
      label: '电子邮件',
      rules: [
        {
          // @ts-ignore
          validator: async (rule, value) => {
            const emailRegex =
              /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
            if (emailRegex.test(value) === false) {
              return Promise.reject('电子邮件格式不正确');
            }
            return Promise.resolve();
          },
          trigger: 'change',
        },
      ],
      componentProps: {
        placeholder: '请输入电子邮件',
      },
    },
    {
      field: 'phoneNumber',
      component: 'Input',
      label: '手机号码',
      rules: [
        {
          // @ts-ignore
          validator: async (rule, value) => {
            const regex = /^1[3-9]\d{9}$/;
            if (regex.test(value) === false) {
              return Promise.reject('手机号码格式不正确');
            }
            return Promise.resolve();
          },
          trigger: 'change',
        },
      ],
      componentProps: {
        placeholder: '例如：13123456789',
      },
    },

    {
      field: 'addCustomerProvince',
      component: 'Input',
      label: '省份',

      componentProps: {
        placeholder: '请输入省份',
      },
    },
    {
      field: 'addCustomerCity',
      component: 'Input',
      label: '城市',

      componentProps: {
        placeholder: '请输入城市',
      },
    },
    {
      field: 'postalCode',
      component: 'Input',
      label: '邮政编码',
      rules: [
        {
          // @ts-ignore
          validator: async (rule, value) => {
            const regex = /^\d{6}$/;
            if (regex.test(value) === false) {
              return Promise.reject('邮政编码格式不正确');
            }
            return Promise.resolve();
          },
          trigger: 'change',
        },
      ],
      componentProps: {
        placeholder: '请输入邮政编码',
      },
    },
    {
      field: 'address',
      component: 'Input',
      label: '地址',

      componentProps: {
        placeholder: '请输入地址',
      },
    },

    {
      field: 'addCustomerIllustrate',
      component: 'InputTextArea',
      label: '说明',
      colProps: {
        span: 24,
      },
      componentProps: {
        placeholder: '请输入说明',
      },
    },
  ];
  //弹窗打开时 初始化数据
  const [register, { setModalProps }] = useModalInner(async (data) => {
    resetFields();
    // 初始化已经选择的租户配置
    let tenantProfileInfo = await getTenantProfileInfo();
    tenantProfileId.value = tenantProfileInfo.id;
    tenantConSelect.value = tenantProfileInfo.id.id;
    let params: any = {
      pageSize: 10,
      page: 0,
      sortProperty: 'name',
      sortOrder: 'ASC',
    };
    // 获取租户配置选项列表数据
    let tenantProfileInfoList = await getTenantProfileInfoList(params);
    tenantProfileInfoList.data.forEach((item) => {
      selectOption.value?.push({
        value: item.id.id,
        label: item.name,
      });
    });
    if (data !== true) {
      isEdit.value = true;
      const theCustomersData = await getTheTenantById(data.id);
      customerData.value = theCustomersData;
      setFieldsValue({
        addCustomerTitle: theCustomersData.title,
        addCustomerIllustrate: theCustomersData.additionalInfo.description,
        selectCountry: theCustomersData.country,
        addCustomerCity: theCustomersData.city,
        addCustomerProvince: theCustomersData.state,
        postalCode: theCustomersData.zip,
        address: theCustomersData.address,
        address2: theCustomersData.address2,
        phoneNumber:
          theCustomersData.phone === null ? '' : theCustomersData.phone.replace(/^\+86/, ''),
        EMail: theCustomersData.email,
      });
    } else {
      // 清空表格
      resetFields();
      isEdit.value = false;
    }
    setModalProps({
      loading: false,
      confirmLoading: false,
      ...modalStyleSetting,
    });
  });
  // 表格初始化
  const [registerForm, { validate, resetFields, setFieldsValue }] = useForm({
    layout: 'vertical',
    schemas,
    actionColOptions: {
      span: 24,
    },
    showActionButtonGroup: false,
    ...modalFormStyleSetting,
  });

  //保存
  async function okClick() {
    try {
      const validateFlag = await validate();
      let params: any;
      if (isEdit.value) {
        // 请求参数填充
        customerData.value.title = validateFlag.addCustomerTitle;
        (customerData.value.additionalInfo = {
          description: validateFlag.addCustomerIllustrate,
          homeDashboardId: null,
          homeDashboardHideToolbar: null,
        }),
          (customerData.value.country = 'China');
        customerData.value.city = validateFlag.addCustomerCity;
        customerData.value.state = validateFlag.addCustomerProvince;
        customerData.value.zip = validateFlag.postalCode;
        customerData.value.address = validateFlag.address;
        customerData.value.address2 = validateFlag.address2;
        customerData.value.phone = '+86' + validateFlag.phoneNumber;
        customerData.value.email = validateFlag.EMail;
        params = customerData.value;
      } else {
        let tenantProfile = await getTenantProfile(tenantConSelect.value);
        params = {
          title: validateFlag.addCustomerTitle,
          tenantProfileId: tenantProfile.id,
          additionalInfo: {
            description: validateFlag.addCustomerIllustrate,
            homeDashboardId: null,
            homeDashboardHideToolbar: null,
          },
          country: 'China',
          city: validateFlag.addCustomerCity,
          state: validateFlag.addCustomerProvince,
          zip: validateFlag.postalCode,
          address: validateFlag.address,
          address2: '',
          phone: '+86' + validateFlag.phoneNumber,
          email: validateFlag.EMail,
        };
      }
      await addTheTenant(params);
      emits('closeModelFlag', 'close');
      resetFields();
    } catch (error) {}
  }
</script>
